//
//  JBWHomePictureView.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/7/5.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit
import SDWebImage
//cell间距
private let cellMargin: CGFloat = 5
//cell宽高 计算所得
private let cellWH = (JBWSCREENW - 20 - 2*cellMargin)/3

//cell重用标识
private let cellID = "cellID"
class JBWHomePictureView: UICollectionView {

    //提供一个模型数组 供外界赋值
    var pictureList: [JBWPictureModel]?{
        didSet{
            print("图片个数",pictureList?.count)
            //计算size
            let size = dealPictureViewSizeWith(count: pictureList!.count)
            
            //通过图片个数更新配图的大小的约束
            snp.updateConstraints { (make) in
                make.size.equalTo(size)
            }
            
            //刷新
            reloadData()
        }
        
    }
    
    //通过配图数组的count来计算配图的size
    private func dealPictureViewSizeWith(count: Int) -> CGSize{
        
        //拿到flowLayout
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        
        //判断是否是一张图片
        if count == 1 {
            //从磁盘中获取本地图片
            if let urlString = pictureList?.first?.thumbnail_pic {
                //通过图片地址获取磁盘保存的图片
                if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: urlString) {
                    //获取图片的宽和高
                    var imageW = image.size.width
                    var imageH = image.size.height
                    //过窄
                    if imageW < 80 {
                        imageW = 80
                    }
                    
                    //过长
                    if imageH > 150 {
                        imageH = 150
                    }
                    //重写设置
                    flowLayout.itemSize = CGSize(width: imageW, height: imageH)
                    //返回
                    return CGSize(width: imageW, height: imageH)
                    
                }
            }
        }
        //通过个数来确定行数列数
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        
        //计算宽高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1) * cellMargin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1) * cellMargin
        
        //重新设置
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        return CGSize(width: w, height: h)
        
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        //itemsize
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        //设置垂直间距和水平间距
        flowLayout.minimumLineSpacing = cellMargin
        flowLayout.minimumInteritemSpacing = cellMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置视图
    private func setupUI(){
        backgroundColor = RGB(r: 235, g: 235, b: 235)
        dataSource = self
        register(JBWHomePictureViewCell.self, forCellWithReuseIdentifier: cellID)
        //为了防止崩溃 可以设置一个默认约束
        snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: cellWH, height: cellWH))
        }
    }
    
   }

//自定义cell
class JBWHomePictureViewCell: UICollectionViewCell {
    
    //供外界赋值
    var pictureModel: JBWPictureModel?{
        didSet{
            //赋值
            bgImageView.jbw_setImage(withUrlString: pictureModel?.thumbnail_pic, placeholderImgName: nil)
            
            guard let thumbnail_pic = pictureModel?.thumbnail_pic else {
                return
            }
            
            //是否显示GIF图片标志
            gifImageView.isHidden = !thumbnail_pic.hasSuffix(".gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    private func setupUI(){
        backgroundColor = UIColor.white
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp.makeConstraints { (make) in
            make.right.bottom.equalTo(contentView)
        }
    }
    //懒加载控件
    private lazy var bgImageView: UIImageView = {
        let img = UIImageView(named: "timeline_image_placeholder")
        //图片填充方式
        img.contentMode = .scaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    
    //gif图片标志
    private lazy var gifImageView: UIImageView = UIImageView(named: "timeline_image_gif")

}
//数据源方法
extension JBWHomePictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! JBWHomePictureViewCell
        cell.pictureModel = pictureList![indexPath.item]
        return cell
    }
}


